import { AxiosError } from 'axios';
import { ApiReply } from './ApiReply';
import { Http, RequestConfig } from './Http';

export const friendlyError = (e: any) => {
  if (e instanceof AxiosError) {
    switch (e.code) {
      case 'ERR_NETWORK': // FIXME: 需要一个合理的国际化的方法。-Gim
        e.message = '网络异常';
        break;
    }
  }
  throw e;
}

export class ApiHttp extends Http {
  GET<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.GET<Reply>(args).then(v => v.data).catch(friendlyError)
  }
  POST<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.POST<Reply>(args).then(v => v.data).catch(friendlyError)
  }
  OPTIONS<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.GET<Reply>(args).then(v => v.data).catch(friendlyError)
  }
  HEAD<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.HEAD<Reply>(args).then(v => v.data).catch(friendlyError)
  }
  PUT<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.PUT<Reply>(args).then(v => v.data).catch(friendlyError)
  }
  DELETE<Data = any, Reply = ApiReply<Data>, Body = any>(args: RequestConfig<Body>): Promise<Reply> {
    return super.DELETE<Reply>(args).then(v => v.data).catch(friendlyError)
  }
}

export const apiHttp = new ApiHttp();